<?php

include_once (S_ROOT . './source/function_user.php');
include_once (S_ROOT . './source/api_class.php');

class Data {
    public $id;
    public $uid;
    public $type;
    public $token;
    public $access;
    public $tpls;
    public $list_name;
    public $apis;
    public $start  = 0;
    public $length = 50;
    public $packType;
    public $scope;
    public function __construct($uid, $type, $token, $access, $id) {
        $this->id    = $id;
        $this->uid   = $uid;
        $this->type  = $type;
        $this->token = $token;
        $this->access= $access;
        $this->tpls       = array('templets'=>'手账模板','stickers' => '贴纸', 'papers' => '背景', 'tags' => '标签', 'brushs' => '花边笔','frames'=>'边框','plugins'=>'插件','bootmgrs'=>'引导器');
        $this->list_name  = array('stickers', 'papers', 'tags', 'brushs','templets','frames','plugins','bootmgrs');
        $this->apis       = array(
                                'list'      =>  array('getPlannerTempletsList','getPlannerTagsList', 'getPlannerPapersList', 'getPlannerStickersList', 'getPlannerBrushsList','getPlannerFramesList','getPlannerPluginsList','getPlannerBootmgrsList'),
                                'detail'    =>  array('getPlannerTempletsDetail','getPlannerTagsDetail','getPlannerPapersDetail','getPlannerStickersDetail','getPlannerBrushsDetail','getPlannerFramesDetail','getPlannerPluginsDetail','getPlannerBootmgrsDetail'),
                                'add'       =>  array('addPlannerTemplets','addPlannerTags','addPlannerPapers', 'addPlannerStickers','addPlannerBrushs','addPlannerFrames','addPlannerPlugins','addPlannerBootmgrs'),
                                'edit'      =>  array('editPlannerTemplets','editPlannerTags','editPlannerPapers','editPlannerStickers','editPlannerBrushs','editPlannerFrames','editPlannerPlugins','editPlannerBootmgrs'),
                                'batch'     =>  array('setBatchData'),
                                'update'    =>  array('updatePlanner'),
        );
        $this->packType  = array('getPlannerTagsList'=>6,'getPlannerPapersList'=>7,'getPlannerStickersList'=>8,'getPlannerBrushsList'=>9,'getPlannerFramesList'=>11,'getPlannerPluginsList'=>12,'getPlannerBootmgrsList'=>13);
        //array('addPlannerTags','addPlannerPapers', 'addPlannerStickers','addPlannerBrushs','addPlannerPlugins','addPlannerFrames','editPlannerPlugins','editPlannerFrames','editPlannerTags','editPlannerPapers','editPlannerStickers','editPlannerBrushs')
        $this->scope = array(
            'addPlannerTags' => array('min'=>80001,'max'=>89999),
            'addPlannerPapers' => array('min'=>50001,'max'=>59999),
            'addPlannerStickers' => array('min'=>60001,'max'=>69999),
            'addPlannerBrushs' => array('min'=>70001,'max'=>79999),
            'addPlannerFrames' => array('min'=>100001,'max'=>109999),
            'addPlannerPlugins' => array('min'=>110001,'max'=>119999),
            'addPlannerTemplets' => array('min'=>90001,'max'=>99999),
            'addPlannerBootmgrs' => array('min'=>120001,'max'=>129999)
            );
    }
    
    public function execute ($action) {
        $do = $this->getDo ($action);
       
        return $this->$do($action);
    }
   
    public function updatePlanner($action){
        $param = array(
            'do'        =>  'shop',
            'format'    =>  'json',
            'action'    =>  $action,
            'type'      =>  $_GET['type']
        );
        $result =  $this->requestApi($action, $param);
        if($result){
            echo 1;
            exit;
        }
        echo 0;
        exit;
    }
    
    /**
     * 批量操作
     * @param unknown $action
     */
    public function setBatchData($action){
    
    	// 组装请求服务器的数据
    	$param = array(
    			'do'        =>  'shop',
    			'format'    =>  'json',
    			'action'    =>  $action,
    			'uid'       =>  $this->uid,
    			'actionType'=>  strval($_GET['actionType']),
    			'ids'		=>  json_encode($_GET['ids']),
    			'editType'	=>  strval($_GET['editType'])
    	);
    	$result =  $this->requestApi($action, $param);
    	if($result){
    		echo 1;
    		exit;
    	}
    	echo 0;
    	exit;
    }
    
    /**
     * 获取商品列表
     * @param unknown $action
     * @return string
     */
    public function getShopList ($action) {

    	$this->start  = intval($_GET ['start']) > 0 ? intval($_GET ['start']) : 0;
    	$this->length = intval($_GET ['length']) > 0 ? intval($_GET ['length']) : $this->length;
        // 请求表情列表数据
        $result   = $this->shopListRequest($action);

        $list     = $this->resultListData($result);

        $data = $this->styleVariable($action);
        $data['packtype']   = $this->packType[$action];
        $data['categories'] = $this->rebuiltCategory($result['categories']);
        $data['list']       = $this->getCategoryName($list,$data['categories']);

        $mpurl  = 'planner.php?ac=class&op='.$action;
        $nextStart = $this->start + $this->length;
        $prevStart = ($this->start > $this->length) ? $this->start-$this->length : 0;
        // 通用变量
        $data['nextpurl']     = $mpurl.'&start='.$nextStart.'&length='.$this->length;
        $data['prevpurl']     = $mpurl.'&start='.$prevStart.'&length='.$this->length;
        $data['mpurl']        = $mpurl;
        $data['firstpurl']    = $mpurl;
        $data['currtenPage']  = intval($this->start)/intval($this->length)+1;

        // 模板渲染到'palnner_list.html'页面,用到的变量为render第二个参数中的数据
        return $this->render('admin/planner_list', $data);
    }

    /**
     *重组分类数据
     * @param $categories
     */
    public function  rebuiltCategory($categories){
        if(empty($categories)){
            return array();
        }
        $res = array();
       foreach($categories as $val){
           $res[$val['cid']] = $val['name'];
       }
        return $res;
    }
    /**
     * 商品名替换
     * @param $list
     * @param $categories
     */
    public function getCategoryName($list, $categories){

       foreach($list as &$value){
           if(empty($categories)){
               break;
           }
           $value['categoryNum'] = $value['category'];
           $value['category'] = $categories[$value['category']];
       }
        return $list;
    }
    /**
     * 获取商品详情
     * @param unknown $action
     * @return string
     */
    public function getShopDetail ($action) {
    
        // 请求表情详情数据
        $result   = $this->shopDetailRequest($action);

        $detail   = $this->goodsDetailData($result);
       
        // 通用变量
        $data = $this->styleVariable($action);
        $data['detail'] = $detail;
        $data['categories'] = $this->rebuiltCategory($result['categories']);
        // 模板渲染到'shop_detail.html'页面,用到的变量为render第二个参数中的数据
        return $this->render('admin/planner_detail', $data);
    }
    
    // 编辑商品
    public function editShop ($action) {
    	
        // 请求表情详情数据
        $result   = $this->shopEditRequest($action);
        $ac=substr($action, 4);
        $a = "get".$ac."List";
        if ($result) {
          showmessage('更新成功','planner.php?ac=class&op='.$a);
        }
        
        return FALSE;
    }
    
    public function addShop ($action) {
        // 请求表情详情数据
        $result   = $this->shopAddRequest($action);
    
        if ($result) {
            echo 1;
            exit;
        }
    
        echo 0;
    }
    
    // 请求服务器商店列表数据
    private function shopListRequest ($action) {
        // 组装请求服务器的数据
        $param = array(
        	'do'        =>  'shop',
        	'format'    =>  'json',
            'action'    =>  $action,
            'uid'       =>  $this->uid,
            'type'      =>  $this->type,
            'id'        =>  $this->id,
            'start'     =>  $this->start,
            'length'    =>  $this->length
        );
        $result=$this->requestApi($action, $param);
        
        return $result;
    }
    
    // 请求服务器商品详情数据
    private function shopDetailRequest ($action) {
        $param = array(
        	'do'        =>  'shop',
        	'format'    =>  'json',
            'action'    =>  $action,
            'uid'       =>  $this->uid,
            'id'        =>  $this->id,
        );
     
        return $this->requestApi($action, $param);
    }
    
    // 请求服务器编辑商品
    private function shopEditRequest ($action) {
        $param = $this->goodsEditOrAddData($action);
        
        return $this->requestApi($action, $param);
    }
    
    // 请求服务器添加商品
    private function shopAddRequest ($action) {
        if(!$this->verifyId($action)){
            return false;
        }
        $param = $this->goodsEditOrAddData($action);
       
        return $this->requestApi($action, $param);
    }

    private function verifyId($action){
        $id = intval($_GET['id']);
        $res = false;
        if($this->scope[$action] && $id >= $this->scope[$action]['min'] && $id <=$this->scope[$action]['max']){
            $res = true;
        }
        return $res;
    }

    private function goodsEditOrAddData ($action) {
        $info = array(
            'id'              =>    empty($_GET['id'])? 0 : intval($_GET['id']),
            'name'            =>    empty($_GET['name'])? '' :strval($_GET['name']),  
            'status'          =>    isset($_GET['status'])? intval($_GET['status']): 1,
            'label'           =>    empty($_GET['label'])? 0 :intval($_GET['label']),
            'category'        =>    intval($_GET['category']),     		
            'vip'             =>    empty($_GET['vip'])? 0 :intval($_GET['vip']),
            'name_tag'        =>    empty($_GET['name_tag'])? 0 :intval($_GET['name_tag']),
            'tag'             =>    empty($_GET['tag'])? '' :strval($_GET['tag']),
            'zip_size'        =>    empty($_GET['zip_size'])? 1024 :intval($_GET['zip_size']),
            'zip_url'         =>    empty($_GET['download_url'])? '' :strval($_GET['download_url']),
            'sale_amount'     =>    empty($_GET['sale_amount'])? 1 :intval($_GET['sale_amount']),
            'price_orign'     =>    empty($_GET['price_orign'])? 0 :intval($_GET['price_orign']),
            'price_final'     =>    empty($_GET['price_final'])? 0 :intval($_GET['price_final']),
            'cuid'            =>    empty($_GET['cuid'])? 3 :intval($_GET['cuid']),
            'desc'            =>    empty($_GET['desc'])? '':strval($_GET['desc']),
            'cover'           =>    empty($_GET['cover'])? 'static/img/default_sz.jpg':strval($_GET['cover']),
            'cover_s'         =>    empty($_GET['cover_s'])? 'static/img/default_sz.jpg':strval($_GET['cover_s']),
            'background'      =>    empty($_GET['background'])? '':strval($_GET['background']),
        	'data'			  =>	'',
            'thumbnail'       =>    $this->thumbailImportData($action, $_GET['thumbnail_m'], $_GET['thumbnail_s']),
            'task'            =>    $this->taskImportData(),
            'action'          =>    $action,
        	'do'        =>  'shop',
        	'format'    =>  'json',
        );
        if(isset($_GET['versionsupport'])){
          $info['versionsupport'] =  $this->minVersionSupport($_GET['versionsupport']);
        }
        return $info;
    }

    private function minVersionSupport($versionsupport){

        $versionsupport = trim($versionsupport);
        $versionArr = explode('|',$versionsupport);
        if(!is_array($versionArr) || empty($versionsupport)){
            return '';
        }
        $pinkdiaryios       = !empty($versionArr[0])?$versionArr[0]:0;
        $pinkdiaryandroid   = !empty($versionArr[1])?$versionArr[1]:0;
        $pinkdiaryproios    = !empty($versionArr[2])?$versionArr[2]:0;
        $version = array(
            'pinkdiaryios'      =>  $pinkdiaryios,
            'pinkdiaryandroid'  =>  $pinkdiaryandroid,
            'pinkdiaryproios'   =>  $pinkdiaryproios
            );
        return json_encode($version);
    }
    private function goodsDetailData ($result) {
        if (empty($result)) return array();
      
        // 通用显示
        $key_arr = array('id', 'name', 'desc', 'cover', 'cover_s','background', 'expire_time', 'vip',
            'dateline','zip_size', 'sale_amount','price_orign', 'price_final', 'download_url'
        );
        $data = $this->assembleReplacedFieldData($result, $key_arr);
      
        // 状态显示
        $status     = $result['status'];
        $status_css = $this->cssShowSelected($status);

        // 资源样式显示
        $name_tag     = $result['name_tag']['bg'];
        $name_tag_css = $this->cssShowSelected($name_tag);
        
        // vip样式显示
        $vip     = $result['vip'];
        $vip_css = $this->cssShowSelected($vip);
        
        // 标签显示
        $tag     = $result['tag'][0]['bg'];
        $tag_css = array();
        if (!empty($tag)) {
            $tag_css = $this->cssShowSelected($tag);
        }
        
        //是否推荐
        $label 		= $result['label'];
        $label_css	= $this->cssShowSelected($label);
        
        //类型
        $category     = $result['category'];
        $category_css = $this->cssShowSelected($category); 
        
        // 任务
        $task = '';
       
        if (!empty($result['task'])) {
            //$task = implode('|', array_slice($result['task'], 0, 3));
            $task_type=$result['task']['type'];
            $task_num =$result['task']['num'];
            $task_msg =$result['task']['desc'];
        }
        
        $data['data'] = empty($result['data'])?'':var_json_encode($result['data']);
        // 预览图显示(根据不同)
        $thumbnail = $this->thumbailExportData($result['download_url'], $result['thumbnail']);
         
        // 商品作者
        $author_uid 			= $result['author']['uid'];

        //最低版本支持
        $versionsupport = $this->assembleVersion($result);

        $data['versionsupport']  = $versionsupport;
        $data['category_css']	= $category_css;
        $data['label_css']      = $label_css;
        $data['status_css']     = $status_css;
        $data['name_tag_css']   = $name_tag_css;
        $data['vip_css']        = $vip_css;
        $data['tag_css']        = $tag_css;
        $data['task_type']      = $task_type;
        $data['task_num']       = $task_num;
        $data['task_msg']       = $task_msg;
        $data['thumbnail']      = $thumbnail;
        $data['cuid']           = $author_uid;
        
        return $data;
    }

    private function assembleVersion($result){
       if(!$result['versionsupport'] || !is_array($result['versionsupport'])){
          return '';
       }
       foreach($result['versionsupport'] as $value){
          $tmp[]= $value;
       }
       return join('|',$tmp);
    }
    //组装打包的json数据显示数据
    private function assembleData($downloadUrl, $data){
    	$str="";
    	if(!empty($data)){
    		//区分素材和模板
    		if(empty($downloadUrl)){
    			foreach($data['res'] as $key=>$material){
    				//fonts|id|title|cover|name-papers|id|title|cover|name
    				foreach($material as $val){
    					$str.=$val['id'].'|'.$val['title'].'|'.$val['cover'].'|'.$val['name'].'|'.$val['url'].'-';
    				}
    				$str = trim($str,'-');
    				$res[$key]=$str;
    				$str='';
    			}
    			return $res;
    		}else{
    			$str=var_json_encode($data);
    			return $str;
    		}
    	}    	
    	return $str;
    	
    }
    // 组装预览图的显示数据
    private function thumbailExportData ($download_url, $thumbnail) {
    
    	if(empty($download_url)) return array('m' => '', 's' => '');
        $goods_info = $this->parseDownLoadUrl($download_url);
      
        $thumbnail_s = $thumbnail_m = array();
        switch ($goods_info['type']) {
        	//手账：
        	case 'paper':
        		$baseUrl = "http://d.fenfenriji.com/diary/planner/paper/".$goods_info['id']."/priview/";              
                break;        	
        	case 'stickers':
        		$baseUrl = "http://d.fenfenriji.com/diary/planner/stickers/".$goods_info['id']."/priview/";        	
        		break;
        	case 'tags':
        		$baseUrl = "http://d.fenfenriji.com/diary/planner/tags/".$goods_info['id']."/priview/";  
        		break;
        	case 'brushs':
        		$baseUrl = "http://d.fenfenriji.com/diary/planner/brushs/".$goods_info['id']."/priview/";
        		break;
            case 'frames':
                $baseUrl = "http://d.fenfenriji.com/diary/planner/frames/".$goods_info['id']."/priview/";
                break;
            case 'plugins':
                $baseUrl = "http://d.fenfenriji.com/diary/planner/plugins/".$goods_info['id']."/priview/";
                break;
        }
        $url = array();
        foreach($thumbnail as $value){
        	$url[] = mb_substr($value['s'],strlen($baseUrl));
        }
        $thumbnail_s = $thumbnail_m = implode(',',$url);        
        return array('m' => $thumbnail_m, 's' => $thumbnail_s);
    }
    
    // 组装预览图的修改数据
    private function thumbailImportData ($action, $thumbnail_m, $thumbnail_s = '') {

    	if(empty($thumbnail_m)){return '';}

        $thumbs = explode(',', trim($thumbnail_m));

        if (empty($thumbs)) return '';
        
        return json_encode($thumbs);
    }
    
    private function taskImportData () {
        $taskArr = array();
        $task=$_GET['task'];
        !empty($_GET['task_type']) && $task=$_GET['task_type']."|".$_GET['task_num'].'|'.$_GET['task_msg'];
        if (!empty($task)) {
            $taskarray = explode('|', $task);
            $taskArr = array(
                'type'    =>    $taskarray[0],
                'num'     =>    $taskarray[1],
                'desc'    =>    $taskarray[2]
            );
        }
     
        if (empty($taskArr)) return '';
      
       return JsonFormat($taskArr);
    }
    
    // 解析下载包链接的地址
    private function parseDownLoadUrl ($download_url) {
        $parts = parse_url($download_url);
        $path  = trim($parts['path'], '/');
        $path_arr = explode('/', $path);
        if (empty($path_arr)) return array();
        
        $goods_type = $path_arr[1];
        $goods_id   = $path_arr[2];
        $goods_name = substr($path_arr[3], 0, strpos($path_arr[3], '_'));
        if ($goods_type == 'appskin') {
            $goods_id   = $path_arr[3];
            $goods_name = substr($path_arr[4], 0, strpos($path_arr[4], '_'));
        }
        if ($goods_type == 'planner'){
        	$goods_type = $path_arr[2];
        	$goods_id	= $path_arr[3];
        	$goods_name = substr($path_arr[4], 0, strpos($path_arr[4], '_'));
        }
        return array('type' => $goods_type, 'id' => $goods_id, 'name' => $goods_name);
    }
    
    // 样式显示相关变量返回
    private function styleVariable ($action) {
        // 通用变量,样式的显示
        $common = $this->apiAndTplName($action);
    
        $result = array(
            'active'        => array($common['goods'] => " class=\"active\""),         // 侧边栏被选择的样式
            'goods'         => ucfirst($common['goods']),   // 商品名
            'goods_name'    => $common['goods_name'],        // 商品名(中文显示)
            'access'        => $this->access
        );
    
        return $result;
    }
    
    // 样式被选定显示
    private function cssShowActive ($attribute) {
        return array($attribute => " class = \" active\"");
    }
    
    // 样式被选定显示
    private function cssShowSelected ($attribute) {
        return array($attribute => " selected");
    }
    
    
    // 处理返回的数据，返回模板渲染用的数据
    private function resultListData ($result) {
        if (empty($result)) return array();
    
        // 处理返回数据
        foreach ($this->list_name as $tpl) {
            if (!empty($result[$tpl])) {
                return $result[$tpl];
            }
        }
    
        return array();
    }
    
    // 组装返回模板及其他需要的变量
    private function apiAndTplName ($action) {
        if (empty($action)) return array();
    
        // 转小写
        $action = strtolower($action);

        // 返回模板名
        foreach ($this->tpls as $good => $name) {
            if (strpos($action, $good)) {
                if ($this->type == 'vip') {
                    $good = 'pro'.$good;
                    return array('goods' => $good, 'goods_name' => $this->tpls [$good]);
                }
                return array('goods' => $good, 'goods_name' => $name);
            }
        }
    
        return array();
    }

    // 返回通用字段
    private function assembleReplacedFieldData ($import, $key_arr = array()) {
        if (empty($key_arr)) {
            return $import;
        }
    
        $result = array();
        foreach ($key_arr as $val) {
            if (isset($import[$val])) {
                $result[$val] = strval($import[$val]);
            }
        }
    
        return $result;
    }
    
    // 获取请求方法
    private function getDo ($action) {
        $do = '';
        switch ($action) {
            case in_array($action, $this->apis['list']) :
                $do = 'getShopList';
                break;
            case in_array($action, $this->apis['detail']) :
                $do = 'getShopDetail';
                break;
            case in_array($action, $this->apis['add']) :
                $do = 'addShop';
                break;
            case in_array($action, $this->apis['edit']) :
                $do = 'editShop';
                break;
            case in_array($action, $this->apis['buy']) :
                $do = 'buyShop';
                break;      
            case in_array($action, $this->apis['batch']) :
                $do = 'setBatchData';
                break;
            case in_array($action, $this->apis['update']) :
                $do = 'updatePlanner';
                break;
        }
                            
        return $do;  
    }
    
    // 请求api
    private function requestApi ($action, $param) {
        // 实例化
        global $_SC;
        $param['action'] = $action;
      	
        $result=get_api_content($_SC ['apiurl'], $param);
       
        $result=json_decode($result,TRUE);
        $result=$result['resultData'];
        // 请求管理接口返回数据
      
        return $result;
    }
    
    // 模板渲染
    private function render ($tpl, $data) {
        // 从数组中把变量导入到当前的符号表中
        extract($data, EXTR_SKIP);
        
        // 使用全局变量
        global $_SGLOBAL;
        
        // 开始输出缓冲, 这时PHP停止输出, 在这以后的输出都被转到一个内部的缓冲里.
        ob_start();
        
        try {
            // 加载本地模板
            include template($tpl);
        } catch (Exception $e) {
            // 删除输出缓冲区
            ob_end_clean();
        
            // 抛出异常
            throw $e;
        }
        
        // 结束输出缓冲, 并扔掉缓冲里的内容.
        return ob_get_clean();
    }
}

// 管理员
$id       = 0;
$type     = 'all';
$uid      = $_SGLOBAL ['supe_uid'];
$token    = $_SGLOBAL['token'];
$action   = 'getPlannerTagsList';
$access   = in_array($uid,$_SGLOBAL['adminuids']);
if ($_GET['id'])   $id     = intval($_GET['id']);
if ($_GET['op'])   $action = strval($_GET['op']);
if ($_GET['type']) $type = strval($_GET['type']);

// 初始化
$data = new Data($uid, $type, $token, $access, $id);
echo $data->execute($action);